import { createRouter, createWebHashHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import localCache from '@/utils/cache';
import { firstMenu } from '@/utils/mapMenus';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main', // 需要动态添加路由, 必须加上name;
    component: () => import('@/views/main/main.vue'),
    children: [
      // 每次到main里面我们都让它去核心技术的模块.
      /* {
        path: '/main',
        redirect: '/main/analysis/overview'
      } */
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/views/not-found/not-found.vue')
  }
];

const router = createRouter({
  routes,
  history: createWebHashHistory()
});

router.beforeEach((to) => {
  // 如果你当前不在登入页面
  if (to.path !== '/login') {
    // 如果没有token就跳到登入页面.
    const token = localCache.getCache('token');
    if (!token) {
      return '/login';
    }
  }

  // console.log(router.getRoutes());
  // console.log(to);

  // 如果是到main,就跳转到第一个注册的menu上.
  if (to.path === '/main') {
    return firstMenu.url;
  }
});

export default router;
